package de.uniwue.cs.ir.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.uniwue.cs.ir.common.Config;
import de.uniwue.cs.ir.vsr.CorpusImpl;
import de.uniwue.cs.ir.vsr.DocumentImpl;
import de.uniwue.cs.ir.vsr.ICorpus;
import de.uniwue.cs.ir.vsr.IDocument;

/**
 * Servlet implementation class SearchServlet
 */
@WebServlet("/SearchServlet")
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ICorpus corpus;

    /**
     * Default constructor. 
     * @throws IOException 
     */
    public SearchServlet() throws IOException {
    	corpus = new CorpusImpl();
    	
    	File dir = Config.getCorpusDir();
		for (File file : dir.listFiles()) {
			if (!file.isDirectory()) {
				FileInputStream stream = new FileInputStream(file);
				IDocument doc = new DocumentImpl(file.getName());
				doc.read(stream);
				stream.close();
				corpus.addDocument(doc);
			}
		}
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("doget");
		String searchTerms = request.getParameter("terms");
		String operator = request.getParameter("operator");
		
		StringTokenizer st = new StringTokenizer(searchTerms);
		Collection<String> tokenList = new ArrayList<String>();
	     while (st.hasMoreTokens()) {
	         tokenList.add(st.nextToken());
	     }
	     
	     String[] tokenListArray = new String[tokenList.size()];
	     tokenListArray = tokenList.toArray(tokenListArray);
		Collection<IDocument> docs = null;
		if (operator.equals("AND")){
			docs = corpus.getDocumentsContainingAll(tokenListArray);
		} else {
			docs = corpus.getDocumentsContainingAny(tokenListArray);
		}
		
		corpus.iterator();
		 request.setAttribute("searchresults", docs);
		
		System.out.println(searchTerms + " " + operator);
		System.out.println("valami> " + docs.size());
		getServletContext().getRequestDispatcher("/SearchResults.jsp").forward(request, response); 
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("dopost");
	}

}
